package com.bw.rbac.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

import javax.sql.DataSource;

@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("select username,password,enabled from tb_user where username=?")
                .authoritiesByUsernameQuery("select username,authority from tb_authority where username=?")
                .passwordEncoder(NoOpPasswordEncoder.getInstance());// 数据库存放的是明码
     //   super.configure(auth);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        http.authorizeRequests()
                .antMatchers("/login","/user/logoutok","/user/noLogin","/mylogin.html","/user/foretPassword","/user/register").permitAll()  //表示允许
                .antMatchers("/**").authenticated()  // 需要认证的
                .and().
              //      formLogin().loginPage("/mylogin.html")// 登录页
                formLogin().loginPage("/user/noLogin")// 要求用户登录
                .loginProcessingUrl("/myprocesslogin") // 接受用户名和密码的资源地址
                .successForwardUrl("/user/loginOk") // 登录成功以后跳转的资源地址  需要自己提供 反馈给前端
                .failureForwardUrl("/user/loginfailed") // 登录失败后跳转的资源地址
                .and().logout().logoutUrl("/mylogoutaaaa")// 处理登出的资源地址  不我要自己提供
                .logoutSuccessUrl("/user/logoutok")  // 登出以后处理的地址
        ;
        http.headers().cacheControl();// 不需要缓存控制
        http.csrf().disable();// 禁用跨域攻击
        http.cors(); //允许跨域访问
    }
}
